<template>
  <div class="voice-recorder" @touchstart="handleTouchStart" @touchmove="handleTouchMove" @touchend="handleTouchEnd" @touchcancel="handleTouchCancel">
    <div v-if="isRecording" class="recording-indicator">
      正在说话...
    </div>
    <div v-else class="record-button">
      {{ buttonText }}
    </div>
  </div>
</template>

<script>
import { initCOS } from '../../utils/upload';
export default {
  data () {
    return {
      isRecording: false,
      isCancelled: false,
      startY: 0,
      duration: 0,
      intervalId: ''
    };
  },
  computed: {
    buttonText () {
      return this.isCancelled ? '取消发送' : '按住说话';
    }
  },
  methods: {
    handleTouchStart (event) {
      this.isRecording = true;
      this.isCancelled = false;
      this.startY = event.touches[0].clientY;
      this.startRecording()
    },
    handleTouchMove (event) {
      const currentY = event.touches[0].clientY;
      const deltaY = currentY - this.startY;
      this.isCancelled = deltaY < -50; // 根据实际情况调整上滑取消发送的阈值
      this.isRecording = deltaY > -50
    },
    handleTouchEnd () {
      this.stopRecording()
      if (this.isRecording) {

        console.log("🚀 ~ file: index.vue:48 ~ handleTouchEnd ~ 发送录音逻辑:")
      } else {
        // 取消发送逻辑
        console.log("🚀 ~ file: index.vue:42 ~ handleTouchEnd ~ 取消发送逻辑:")
        this.deleteRecording();
      }
      this.resetRecordingState();
    },
    handleTouchCancel () {
      this.resetRecordingState();
    },
    deleteRecording () {
      // 删除录音逻辑
      this.resetRecordingState();
      // 清除定时器
      clearInterval(this.intervalId);
    },
    resetRecordingState () {
      this.isRecording = false;
      this.isCancelled = false;
      this.startY = 0;
    },
    startRecording () {
      this.duration = 0
      console.log("🚀 ~ file: index.vue:69 ~ startRecording ~ this.duration:", this.duration)
      this.intervalId = setInterval(() => {
        this.duration++;
        if (this.duration >= 60) {
          this.stopRecording();
          clearInterval(this.intervalId);
        }
        console.log('11', this.duration)
      }, 1000);
      navigator.mediaDevices.getUserMedia({
        audio: true
      })
        .then((stream) => {
          this.isRecording = true;
          this.chunks = [];
          this.mediaRecorder = new MediaRecorder(stream);
          this.mediaRecorder.addEventListener('dataavailable', (event) => {
            this.chunks.push(event.data);
            console.log('event.data', event.data)
            clearInterval(this.intervalId);
          });
          this.mediaRecorder.start();
        })
        .catch((error) => {
          this.$toast('error', '无法访问麦克风')
          clearInterval(this.intervalId);
        });
    },
    stopRecording () {
      if (this.mediaRecorder && this.isRecording) {
        this.mediaRecorder.addEventListener('stop', async () => {
          this.isRecording = false;
          const blob = new Blob(this.chunks, {
            type: 'audio/mp3'
          });
          this.recordedBlob = new File([blob], 'audio.mp3', { type: 'audio/mp3' });
          // 发送录音逻辑
          const voice = await initCOS(this.recordedBlob, '', true, '', true);
          this.$emit('voice', { voice: voice, time: this.duration })
          console.log("🚀 ~ file: index.vue:91 ~ this.mediaRecorder.addEventListener ~ blob:", this.recordedBlob)
        });
        this.mediaRecorder.stop();
      }
    },
  }
};
</script>

<style scoped>
.voice-recorder {
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100%;
}

.recording-indicator {
  font-weight: bold;
}

.record-button,
.cancel-indicator {
  cursor: pointer;
}

.delete-button {
  position: absolute;
  bottom: 5px;
  right: 5px;
  color: red;
  cursor: pointer;
}
</style>